/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.celularessuc.gco.ui;

import com.jjsoft.celularessuc.gco.mdl.DeudaCliente;
import com.jjsoft.celularessuc.gco.mdl.Ingreso;
import com.jjsoft.celularessuc.gco.mdl.Mensualidad;
import com.jjsoft.celularessuc.gco.neg.DiarioManager;
import com.jjsoft.celularessuc.gco.neg.IngresoManager;
import com.jjsoft.celularessuc.gco.neg.MensualidadManager;
import com.jjsoft.celularessuc.gco.util.CNumeros;
import com.jjsoft.celularessuc.gco.util.MiModelo;
import com.jjsoft.celularessuc.gco.util.configuraciones;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JOptionPane;

/**
 *
 * @author javila
 */
public class VPagoMensualidad extends javax.swing.JFrame {

    /**
     * Creates new form VPagoMensualidad
     */
    DeudaCliente deuda;
    List<Mensualidad> Mensualidades;
    MensualidadManager mm = new MensualidadManager();
    double cuota;
    double capitalPagado = 0;
    double interesPagado = 0;
    double totalPagado = 0;
    JButton boton;

    public VPagoMensualidad() {
        initComponents();
    }

    public VPagoMensualidad(DeudaCliente deuda, JButton boton) {
        initComponents();
        this.deuda = deuda;
        Mensualidades = mm.listarPagos(deuda);
        txtCliente.setText(deuda.getCedulaCliente().getNombres() + " " + deuda.getCedulaCliente().getApellidos());
        txtSaldoActual.setText(CNumeros.Formato(deuda.getSaldoActual()));
        cargarMensualidades();
        this.boton = boton;

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel6 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtSaldoActual = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtCliente = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgPagos = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        txtCuota = new javax.swing.JTextField();
        cmdPagarMensualidad = new javax.swing.JButton();
        cmdPagoAdelantado = new javax.swing.JButton();
        cmdCancelar = new javax.swing.JButton();
        cmdGuardarCambios = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel6.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        jLabel6.setForeground(new java.awt.Color(0, 51, 255));
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel6.setText("Pago de Mensualidades");

        jLabel1.setText("Saldo Actual:");

        txtSaldoActual.setEditable(false);

        jLabel2.setText("Cliente:");

        txtCliente.setEditable(false);

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(255, 0, 0));
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Detalle de Pagos");

        dtgPagos.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        dtgPagos.setEnabled(false);
        dtgPagos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(dtgPagos);

        jLabel3.setText("Cuota Mensual:");

        txtCuota.setEditable(false);

        cmdPagarMensualidad.setText("Registrar pago Mensualidad");
        cmdPagarMensualidad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdPagarMensualidadActionPerformed(evt);
            }
        });

        cmdPagoAdelantado.setText("Registrar pago Adelantado");
        cmdPagoAdelantado.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cmdPagoAdelantadoMouseClicked(evt);
            }
        });
        cmdPagoAdelantado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdPagoAdelantadoActionPerformed(evt);
            }
        });

        cmdCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete.png"))); // NOI18N
        cmdCancelar.setText("Cancelar");

        cmdGuardarCambios.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/save.png"))); // NOI18N
        cmdGuardarCambios.setText("Guardar Cambios");
        cmdGuardarCambios.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdGuardarCambiosActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 727, Short.MAX_VALUE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtSaldoActual, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCliente))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmdPagarMensualidad)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmdPagoAdelantado))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCuota, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(cmdGuardarCambios))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cmdCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtSaldoActual, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtCuota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdPagarMensualidad)
                    .addComponent(cmdPagoAdelantado))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cmdCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cmdGuardarCambios, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void cmdPagarMensualidadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdPagarMensualidadActionPerformed
        // TODO add your handling code here:
        for (int i = 0; i < Mensualidades.size(); i++) {
            if (Mensualidades.get(i).getEstado()) {
                Mensualidades.get(i).setEstado(false);
                capitalPagado += Mensualidades.get(i).getCapital();
                interesPagado += Mensualidades.get(i).getInteres();
                totalPagado += Mensualidades.get(i).getCouta();
                cargarMensualidades();
                break;
            }
        }
    }//GEN-LAST:event_cmdPagarMensualidadActionPerformed

    private void cmdPagoAdelantadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdPagoAdelantadoActionPerformed
        // TODO add your handling code here:

    }//GEN-LAST:event_cmdPagoAdelantadoActionPerformed


    private void cmdPagoAdelantadoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cmdPagoAdelantadoMouseClicked
        // TODO add your handling code here:
        if (JOptionPane.showConfirmDialog(rootPane, "Al registrar un pago adelantado la deuda se recalculará\n Desea continuar?", "Registrar pago adelantado", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            String valor = JOptionPane.showInputDialog("Ingrese el valor del adelanto");
            if (valor != null) {
                if (valor.trim().equals("")) {
                    JOptionPane.showMessageDialog(rootPane, "Ingrese un valor", "Error", JOptionPane.ERROR_MESSAGE);
                } else {
                    try {
                        double valor_adelanto = Double.parseDouble(valor);
                        recalculaDeuda(valor_adelanto);
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(rootPane, "Formato de valor de adelanto incorrecto", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        }
    }//GEN-LAST:event_cmdPagoAdelantadoMouseClicked

    private void cmdGuardarCambiosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdGuardarCambiosActionPerformed
        // TODO add your handling code here:
        if (JOptionPane.showConfirmDialog(rootPane, "Esta seguro?", "Guardar Cambios", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            mm.registrarPagos(Mensualidades, deuda);
            Date d = new Date();
            IngresoManager im = new IngresoManager();
            Ingreso ingreso = new Ingreso();
            ingreso.setIdUsuario(configuraciones.getInstance().getUsuario());
            ingreso.setFecha(d);
            ingreso.setConcepto("Pago de deuda");
            ingreso.setValor(totalPagado);
            ingreso.setHora(d.toLocaleString().substring(d.toLocaleString().indexOf(" ")));
            im.registrarIngreso(ingreso);
            DiarioManager dm = new DiarioManager();
            String fecha = d.toLocaleString().split(" ")[0];
            configuraciones.getInstance().getDiario().setValor(configuraciones.getInstance().getDiario().getValor() + totalPagado);
            dm.editarDiario(configuraciones.getInstance().getDiario());
            VPrincipal.getInstance().cambiaCaja(configuraciones.getInstance().getDiario().getValor());
            JOptionPane.showMessageDialog(rootPane, "Operación realizada correctamente", "Guardar Cambios", JOptionPane.INFORMATION_MESSAGE);
            boton.doClick();
            this.dispose();
        }
    }//GEN-LAST:event_cmdGuardarCambiosActionPerformed

    /**
     * @param args the command line arguments
     */
    private void recalculaDeuda(double adelanto) {
        int i;
        for (i = 0; i < Mensualidades.size(); i++) {
            if (Mensualidades.get(i).getEstado()) {
                break;
            }
        }
        Mensualidades.get(i).setCapital(adelanto - Mensualidades.get(i).getInteres());
        capitalPagado += Mensualidades.get(i).getCapital();
        totalPagado += adelanto;
        interesPagado += Mensualidades.get(i).getInteres();
        Mensualidades.get(i).setSaldoFinal(Mensualidades.get(i).getSaldoInicial() - Mensualidades.get(i).getCapital());
        Mensualidades.get(i).setCouta(adelanto);
        Mensualidades.get(i).setEstado(false);
        double saldoActual = Mensualidades.get(i).getSaldoFinal();
        double interesActual;
        double capitalActual;
        double saldoFinal;
        double interesMensual = Mensualidades.get(i).getPorcInteres();
        i = i + 1;

        for (; i < Mensualidades.size(); i++) {

            Mensualidades.get(i).setSaldoInicial(saldoActual);
            interesActual = saldoActual * interesMensual;
            if (saldoActual + interesActual < cuota) {
                Mensualidades.get(i).setCouta(saldoActual + interesActual);
                Mensualidades.get(i).setCapital(saldoActual);
                Mensualidades.get(i).setSaldoFinal(0d);
                Mensualidades.get(i).setInteres(interesActual);
                break;

            }
            capitalActual = cuota - interesActual;

            saldoFinal = saldoActual - capitalActual;

            Mensualidades.get(i).setCapital(capitalActual);
            Mensualidades.get(i).setSaldoFinal(saldoFinal);
            Mensualidades.get(i).setInteres(interesActual);
            saldoActual = saldoFinal;

        }
        i = i + 1;
        for (; i < Mensualidades.size(); i++) {
            Mensualidades.get(i).setEstado(false);
            Mensualidades.get(i).setCapital(0d);
            Mensualidades.get(i).setCouta(0d);
            Mensualidades.get(i).setInteres(0d);
            Mensualidades.get(i).setPorcInteres(0d);
            Mensualidades.get(i).setSaldoFinal(0d);
            Mensualidades.get(i).setSaldoInicial(0d);
        }
        cargarMensualidades();

    }

    private void cargarMensualidades() {

        MiModelo modelo = new MiModelo();
        String[] identificiadores = {"Pago", "F. Pago", "S.Inicial", "Interes", "Capital", "Couta", "Saldo Final", "Estado"};
        modelo.setColumnIdentifiers(identificiadores);
        if (Mensualidades != null && Mensualidades.size() > 0) {
            txtCuota.setText(CNumeros.Formato(Mensualidades.get(0).getCouta()));
            cuota = Mensualidades.get(0).getCouta();
        }
        for (Mensualidad mensualidad : Mensualidades) {
            String estado;
            if (mensualidad.getEstado()) {
                estado = "Vigente";
            } else {
                estado = "Pagada";
            }
            String fechaDePago = mensualidad.getFechaPago().toLocaleString().split(" ")[0];
            String[] datos = {String.valueOf(mensualidad.getNumPago()), fechaDePago, CNumeros.Formato(mensualidad.getSaldoInicial()), CNumeros.Formato(mensualidad.getInteres()), CNumeros.Formato(mensualidad.getCapital()), CNumeros.Formato(mensualidad.getCouta()), CNumeros.Formato(mensualidad.getSaldoFinal()), estado};
            modelo.addRow(datos);
        }
        this.dtgPagos.setModel(modelo);
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VPagoMensualidad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VPagoMensualidad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VPagoMensualidad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VPagoMensualidad.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VPagoMensualidad().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdCancelar;
    private javax.swing.JButton cmdGuardarCambios;
    private javax.swing.JButton cmdPagarMensualidad;
    private javax.swing.JButton cmdPagoAdelantado;
    private javax.swing.JTable dtgPagos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField txtCliente;
    private javax.swing.JTextField txtCuota;
    private javax.swing.JTextField txtSaldoActual;
    // End of variables declaration//GEN-END:variables
}
